import { useState, useEffect } from 'react';

// 定义离线内容类型
interface OfflineContent {
  id: string;
  name: string;
  type: 'map' | 'translation' | 'guide';
  size: string;
  downloaded: boolean;
  lastUpdated: string;
  progress?: number; // 下载进度，0-100
  downloadId?: string; // 下载任务ID
}

// 存储键
const STORAGE_KEY = 'multilingual_travel_assistant_offline_content';

// 默认离线内容
const DEFAULT_CONTENT: OfflineContent[] = [
  {
    id: '1',
    name: '东京离线地图',
    type: 'map',
    size: '125 MB',
    downloaded: true,
    lastUpdated: '2024-01-15'
  },
  {
    id: '2',
    name: '日语翻译包',
    type: 'translation',
    size: '45 MB',
    downloaded: true,
    lastUpdated: '2024-01-10'
  },
  {
    id: '3',
    name: '大阪离线地图',
    type: 'map',
    size: '98 MB',
    downloaded: false,
    lastUpdated: '2024-01-20'
  },
  {
    id: '4',
    name: '韩语翻译包',
    type: 'translation',
    size: '42 MB',
    downloaded: false,
    lastUpdated: '2024-01-18'
  },
  {
    id: '5',
    name: '日本旅行指南',
    type: 'guide',
    size: '28 MB',
    downloaded: false,
    lastUpdated: '2024-01-25'
  }
];

// 获取存储的离线内容
const getStoredContent = (): OfflineContent[] => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    return stored ? JSON.parse(stored) : DEFAULT_CONTENT;
  } catch (error) {
    console.error('Failed to load offline content from storage:', error);
    return DEFAULT_CONTENT;
  }
};

// 保存离线内容到存储
const saveContentToStorage = (content: OfflineContent[]): void => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(content));
  } catch (error) {
    console.error('Failed to save offline content to storage:', error);
  }
};

// 模拟下载功能
const simulateDownload = (
  content: OfflineContent,
  onProgress: (progress: number) => void,
  onComplete: () => void
): string => {
  const downloadId = Date.now().toString();
  let progress = 0;

  const interval = setInterval(() => {
    progress += 5;
    onProgress(progress);

    if (progress >= 100) {
      clearInterval(interval);
      setTimeout(onComplete, 500); // 模拟完成延迟
    }
  }, 300);

  return downloadId;
};

// 取消下载
const cancelDownload = (downloadId: string): void => {
  // 在实际应用中，这里会取消真实的下载任务
  console.log(`Download ${downloadId} canceled`);
};

// 离线内容服务
const useOfflineContentService = () => {
  const [content, setContent] = useState<OfflineContent[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [downloadingIds, setDownloadingIds] = useState<Record<string, string>>({}); // 存储正在下载的内容ID和下载任务ID

  // 加载离线内容
  useEffect(() => {
    try {
      setContent(getStoredContent());
      setIsLoading(false);
    } catch (err) {
      setError('Failed to load offline content');
      setIsLoading(false);
    }
  }, []);

  // 下载内容
  const downloadContent = (contentId: string) => {
    const itemIndex = content.findIndex(item => item.id === contentId);
    if (itemIndex === -1) return;

    const updatedContent = [...content];
    const item = updatedContent[itemIndex];

    // 已经下载或正在下载的不重复下载
    if (item.downloaded || downloadingIds[contentId]) return;

    // 更新为下载中状态
    updatedContent[itemIndex] = {
      ...item,
      progress: 0
    };
    setContent(updatedContent);

    // 模拟下载
    const downloadId = simulateDownload(
      item,
      (progress) => {
        const newContent = [...content];
        newContent[itemIndex] = {
          ...newContent[itemIndex],
          progress
        };
        setContent(newContent);
      },
      () => {
        const newContent = [...content];
        newContent[itemIndex] = {
          ...newContent[itemIndex],
          downloaded: true,
          progress: undefined,
          downloadId: undefined
        };
        setContent(newContent);
        saveContentToStorage(newContent);
        setDownloadingIds(prev => {
          const { [contentId]: _, ...rest } = prev;
          return rest;
        });
      }
    );

    // 记录下载任务ID
    setDownloadingIds(prev => ({
      ...prev,
      [contentId]: downloadId
    }));
  };

  // 删除内容
  const deleteContent = (contentId: string) => {
    const updatedContent = content.map(item => 
      item.id === contentId ? { ...item, downloaded: false } : item
    );
    setContent(updatedContent);
    saveContentToStorage(updatedContent);
  };

  // 取消下载
  const cancelContentDownload = (contentId: string) => {
    if (downloadingIds[contentId]) {
      cancelDownload(downloadingIds[contentId]);
      setDownloadingIds(prev => {
        const { [contentId]: _, ...rest } = prev;
        return rest;
      });

      // 重置下载状态
      const updatedContent = content.map(item => 
        item.id === contentId ? { ...item, progress: undefined } : item
      );
      setContent(updatedContent);
    }
  };

  // 获取存储空间使用情况
  const getStorageUsage = () => {
    const downloadedItems = content.filter(item => item.downloaded);
    const totalSize = downloadedItems.reduce((sum, item) => {
      const sizeNum = parseFloat(item.size);
      return sum + sizeNum;
    }, 0);
    return {
      used: totalSize,
      total: 1024, // 假设总存储空间为1GB
      usedPercentage: Math.round((totalSize / 1024) * 100)
    };
  };

  return {
    content,
    isLoading,
    error,
    downloadContent,
    deleteContent,
    cancelContentDownload,
    getStorageUsage,
    isDownloading: (contentId: string) => !!downloadingIds[contentId]
  };
};

export default useOfflineContentService;